package com.cdvtc.flower.dao.impl;

import com.cdvtc.flower.dao.CategoryDao;
import com.cdvtc.flower.model.Category;
import com.cdvtc.flower.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CategoryDaoImpl implements CategoryDao {
    private Connection conn;

    @Override
    public List<Category> getAllCategories() {
        List<Category> categories = new ArrayList<>();

        // 获取连接
        conn = DBUtil.getConnection();
//        Statement st = null;


        // 创建Staement
        try(Statement st = conn.createStatement()) {
            // 执行SQL，获取ResultSet
            String sql = "select * from category";
            try(ResultSet rs = st.executeQuery(sql)) {
                // 从rs中获取数据
                while (rs.next()) {
                    int category_id = rs.getInt("category_id");
                    String category_name = rs.getString("category_name");

                    // 将数据写入封装对象
                    Category category = new Category();
                    category.setCategory_id(category_id);
                    category.setCategory_name(category_name);

                    //将对象往往集合类中
                    categories.add(category);
                }
            }

            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return categories;
    }

    @Override
    public void updateCategory(Category category) {
        try (Connection conn = DBUtil.getConnection(); // 使用try-with-resources自动关闭连接
             PreparedStatement pstmt = conn.prepareStatement(
                     "UPDATE category SET  category_name = ?"+
                             "WHERE category_id = ?")) { // 准备SQL语句以更新产品

            // 设置更新的字段值
            pstmt.setString(1, category.getCategory_name());
            pstmt.setInt(2, category.getCategory_id());

            // 执行更新
            pstmt.executeUpdate();

        } catch (SQLException e) {
            // 处理数据库相关的异常
            e.printStackTrace(); // 这只是暂时的，你应该使用更合适的日志记录方法
            // 在这里你可以抛出异常或进行其他错误处理
        }
    }

    public static void main(String[] args) {
        CategoryDao categoryDao = new CategoryDaoImpl();
        List<Category> categoryList = categoryDao.getAllCategories();

        for(Category category: categoryList) {
            System.out.println(category);
        }
    }
}
